package com.lei.app.handler;

import com.lei.app.entity.socket.room.SocketRoom;
import com.lei.app.entity.socket.room.SocketRoomUser;
import com.lei.app.utils.enums.ChatRoomStateEnum;
import com.lei.app.vo.AjaxResult;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.util.cri.Static;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;

import javax.websocket.MessageHandler;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 郑兴泉 956607644@qq.com
 * @data 2020/4/9
 * 描述：
 */
public class DbRoomWsHandler extends AbstractWsHandler implements MessageHandler.Whole<String> {

    protected String nickname;

    public DbRoomWsHandler() {
        super("");
    }

    /**
     * 加入房间 对应的消息是  {action:"join", room:"wendal"}
     */
    public void addOrEditRoom(NutMap req) {
        join(req);
        SocketRoom room =  req.getAs("data",SocketRoom.class);
        if(room != null){
            if(Strings.isNotBlank(room.getUuid())){
                getDao().updateIgnoreNull(room);
            }else{
                getDao().insert(room);
            }
        }
        endpoint.sendTextSync(getSessionId(), Json.toJson(AjaxResult.sucess(ChatRoomStateEnum.ADD_ROOM.getValue())));
    }

    /**
     * 加入房间 对应的消息是  {action:"refreshRoom", room:"wendal"}
     */
    public void refreshRoom(NutMap req) {
        join(req);
        SocketRoom room =  req.getAs("data",SocketRoom.class);
        if(room != null){
            getDao().insertOrUpdate(room);
        }
        endpoint.sendTextSync(getSessionId(), Json.toJson(AjaxResult.sucess(ChatRoomStateEnum.ADD_ROOM.getValue())));
    }


    /**
     * 加入房间 对应的消息是  {action:"join", room:"wendal"}
     */
    public void getRoom(NutMap req) {
        List<Record> erc = getDao().query(SocketRoom.class.getAnnotation(Table.class).value() ,
                Cnd.where("delFlag","=",0).asc("sort"),null,"uuid,name,maxNumber,sysState,note");
        if(erc == null){
            erc = Collections.EMPTY_LIST;
        }
        endpoint.sendTextSync(getSessionId(),Json.toJson(AjaxResult.sucess(erc,String.valueOf(ChatRoomStateEnum.FIND_ALL_ROOM.getValue()))));
    }

    public void findUserByRoomId(NutMap req){
        String roomId =  req.getString("data");
        List<Record> erc =  Collections.EMPTY_LIST;
        if(Strings.isNotBlank(roomId)){
            erc = getDao().query(SocketRoomUser.class.getAnnotation(Table.class).value() ,
                    Cnd.where("delFlag","=",0)
                            .and(new Static("uuid IN (SELECT userId FROM `web_socket_room_user` WHERE roomId = '"+roomId+"')")).desc("sort"),null,"uuid,name,sysState,note");
        }
        endpoint.sendTextSync(getSessionId(),Json.toJson(AjaxResult.sucess(erc,String.valueOf(ChatRoomStateEnum.FIND_USER_WITH_ROOM.getValue()))));
    }


    public void joinRoom(NutMap req){
        String roomId = req.getString("roomId") ,
                userIds = req.getString("userIds");
        // 房间
        join(roomId);
        // 人员数据
        if(Strings.isNotBlank(userIds)){
            getDao().clear("web_socket_room_user",Cnd.where("roomId","=",roomId));
            String[] userIdArray = userIds.split(",");
            List<NutMap> data = new ArrayList<>();
            for (String uid : userIdArray) {
                data.add(NutMap.NEW().setv("roomId",roomId).setv("userId",uid));
            }
            data.get(0).addv(".table","web_socket_room_user");
            getDao().insert(data);
        }
        endpoint.sendTextSync(getSessionId(),Json.toJson(AjaxResult.sucess(String.valueOf(ChatRoomStateEnum.ADD_ROOM_USER.getValue()))));
    }

    /**
     * 加入房间 对应的消息是  {action:"join", room:"wendal"}
     */
    public void join(NutMap req) {
        join(req.getString("room"));
    }

    /**
     * 退出房间 对应的消息是 {action:"left", room:"wendal"}
     */
    public void remove(NutMap req) {
        remove(req.getString("room"));
        SocketRoom room =  getDao().fetch(SocketRoom.class,req.getString("id"));
        if(room != null){
            room.setDelFlag(true);
            room.setOpAt(new Timestamp(System.currentTimeMillis()));
            getDao().insertOrUpdate(room);
        }
        endpoint.sendTextSync(session.getId(), Json.toJson(AjaxResult.sucess(ChatRoomStateEnum.REMOVE_ROOM.getValue())));
    }

    /**
     * 设置昵称
     */
    public void nickname(NutMap req) {
        String nickname = req.getString("nickname");
        if (!Strings.isBlank(nickname)) {
            this.nickname = nickname;
        }
    }
}
